package config

import (
	"bytes"
	"database/sql"
	e "db_ping/err"
	_ "github.com/go-sql-driver/mysql"
)

const (
	//:
	colon = ":"
	// \/
	slash = "/"
	//@
	aite = "@"
)

type RunSqlConfig struct {
	Username string
	Password string
	Url      string
}

func GetConnection(cfg *SqlConfig, r *RunSqlConfig) *sql.DB {
	db1, err := sql.Open(cfg.Drivername, DataSourceName(r))
	e.CheckDBErr(err)
	db1.SetMaxIdleConns(1)
	db1.SetMaxOpenConns(2)
	errping := db1.Ping()
	e.CheckErrPing(cfg.TaskName, errping)
	return db1
}

func DataSourceName(r *RunSqlConfig) string {
	var dataSourceName bytes.Buffer
	dataSourceName.WriteString(r.Username)
	dataSourceName.WriteString(colon)
	dataSourceName.WriteString(r.Password)
	dataSourceName.WriteString(aite)
	dataSourceName.WriteString(r.Url)
	return dataSourceName.String()
}
